<template>
  <div class="user-works">
    <div class="works-header">
      <h2>我的作品</h2>
      <div class="header-actions">
        <select v-model="sortBy" class="sort-select">
          <option value="latest">最新发布</option>
          <option value="popular">最受欢迎</option>
          <option value="views">浏览最多</option>
        </select>
        <button @click="showUploadModal = true" class="upload-btn">
          <span class="icon">+</span>
          上传作品
        </button>
      </div>
    </div>
    
    <div class="works-filter">
      <button 
        v-for="category in categories" 
        :key="category.key"
        @click="activeCategory = category.key"
        :class="['filter-btn', { active: activeCategory === category.key }]"
      >
        {{ category.label }}
      </button>
    </div>
    
    <div v-if="filteredWorks.length === 0" class="empty-state">
      <div class="empty-icon">🎨</div>
      <h3>还没有作品</h3>
      <p>开始创作你的第一个AI作品吧！</p>
      <button @click="showUploadModal = true" class="create-first-btn">创作第一个作品</button>
    </div>
    
    <div v-else class="works-grid">
      <div v-for="work in filteredWorks" :key="work.id" class="work-card">
        <div class="work-image">
          <img :src="getImageUrl(work.thumbnail)" :alt="work.title" />
          <div class="work-overlay">
            <button @click="viewWork(work)" class="view-btn">查看</button>
            <button @click="editWork(work)" class="edit-btn">编辑</button>
            <button @click="deleteWork(work.id)" class="delete-btn">删除</button>
          </div>
        </div>
        <div class="work-content">
          <h3>{{ work.title }}</h3>
          <p class="work-description">{{ work.description }}</p>
          <div class="work-tags">
            <span v-for="tag in work.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
          <div class="work-stats">
            <div class="stat">
              <span class="icon">👁</span>
              <span>{{ work.views }}</span>
            </div>
            <div class="stat">
              <span class="icon">❤️</span>
              <span>{{ work.likes }}</span>
            </div>
            <div class="stat">
              <span class="icon">💬</span>
              <span>{{ work.comments }}</span>
            </div>
          </div>
          <div class="work-meta">
            <span class="category">{{ getCategoryLabel(work.category) }}</span>
            <span class="date">{{ formatDate(work.createdAt) }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 上传作品模态框 -->
    <div v-if="showUploadModal" class="modal-overlay" @click="closeModal">
      <div class="upload-modal" @click.stop>
        <div class="modal-header">
          <h3>上传作品</h3>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        <form @submit.prevent="uploadWork" class="upload-form">
          <div class="form-group">
            <label>作品标题</label>
            <input v-model="uploadForm.title" type="text" placeholder="请输入作品标题" required />
          </div>
          <div class="form-group">
            <label>作品描述</label>
            <textarea v-model="uploadForm.description" placeholder="描述你的创作过程和灵感..." rows="4"></textarea>
          </div>
          <div class="form-group">
            <label>作品分类</label>
            <select v-model="uploadForm.category" required>
              <option value="">请选择分类</option>
              <option value="image">AI绘画</option>
              <option value="video">AI视频</option>
              <option value="music">AI音乐</option>
              <option value="text">AI文本</option>
            </select>
          </div>
          <div class="form-group">
            <label>标签</label>
            <input v-model="uploadForm.tags" type="text" placeholder="用逗号分隔多个标签" />
          </div>
          <div class="form-group">
            <label>作品文件</label>
            <div class="file-upload">
              <input type="file" @change="handleFileUpload" accept="image/*,video/*,audio/*" required />
              <div v-if="uploadForm.file" class="file-preview">
                <img v-if="uploadForm.fileType === 'image'" :src="uploadForm.preview" alt="预览" />
                <div v-else class="file-info">
                  <span>{{ uploadForm.file.name }}</span>
                  <span>{{ formatFileSize(uploadForm.file.size) }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="button" @click="closeModal" class="cancel-btn">取消</button>
            <button type="submit" class="submit-btn" :disabled="uploading">{{ uploading ? '上传中...' : '发布作品' }}</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '../stores/user';
import { API_BASE_URL } from '../api/config';

// 初始化store
const userStore = useUserStore();
    const showUploadModal = ref(false);
    const uploading = ref(false);
    const loading = ref(false);
    const sortBy = ref('latest');
    const activeCategory = ref('all');

    const categories = [
      { key: 'all', label: '全部' },
      { key: 'image', label: 'AI绘画' },
      { key: 'video', label: 'AI视频' },
      { key: 'music', label: 'AI音乐' },
      { key: 'text', label: 'AI文本' }
    ];

    const uploadForm = ref({
      title: '',
      description: '',
      category: '',
      tags: '',
      file: null,
      fileType: '',
      preview: ''
    });

    // 从store获取用户作品
    const userWorks = computed(() => userStore.userWorks || []);

    const filteredWorks = computed(() => {
      let works = userWorks.value;
      
      // 按分类筛选
      if (activeCategory.value !== 'all') {
        works = works.filter(work => work.category === activeCategory.value);
      }
      
      // 排序
      switch (sortBy.value) {
        case 'popular':
          works = works.sort((a, b) => b.likes - a.likes);
          break;
        case 'views':
          works = works.sort((a, b) => b.views - a.views);
          break;
        default: // latest
          works = works.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      }
      
      return works;
    });

    /**
     * 获取分类标签
     * @param {string} category - 分类键值
     * @returns {string} 分类标签
     */
    const getCategoryLabel = (category) => {
      const cat = categories.find(c => c.key === category);
      return cat ? cat.label : category;
    };

    /**
     * 获取完整的图片URL
     * @param {string} thumbnail - 图片路径
     * @returns {string} 完整的图片URL
     */
    const getImageUrl = (thumbnail) => {
      if (!thumbnail) return '';
      // 如果已经是完整URL，直接返回
      if (thumbnail.startsWith('http')) {
        return thumbnail;
      }
      // 拼接后端baseUrl
      return `${API_BASE_URL}${thumbnail.startsWith('/') ? '' : '/'}${thumbnail}`;
    };

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN');
    };

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const handleFileUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        uploadForm.value.file = file;
        
        // 判断文件类型
        if (file.type.startsWith('image/')) {
          uploadForm.value.fileType = 'image';
          // 创建预览
          const reader = new FileReader();
          reader.onload = (e) => {
            uploadForm.value.preview = e.target.result;
          };
          reader.readAsDataURL(file);
        } else {
          uploadForm.value.fileType = 'other';
        }
      }
    };

    const uploadWork = async () => {
      uploading.value = true;
      try {
        // 调用store中的上传方法
        const workData = {
          title: uploadForm.value.title,
          description: uploadForm.value.description,
          category: uploadForm.value.category,
          tags: uploadForm.value.tags.split(',').map(tag => tag.trim())
        };
        
        await userStore.uploadWork(workData, uploadForm.value.file);
        closeModal();
        alert('作品上传成功！');
      } catch (error) {
        console.error('上传失败:', error);
        alert('上传失败，请重试');
      } finally {
        uploading.value = false;
      }
    };

    const closeModal = () => {
      showUploadModal.value = false;
      uploadForm.value = {
        title: '',
        description: '',
        category: '',
        tags: '',
        file: null,
        fileType: '',
        preview: ''
      };
    };

    const viewWork = (work) => {
      alert(`查看作品: ${work.title}`);
    };

    const editWork = (work) => {
      alert(`编辑作品: ${work.title}`);
    };

    const deleteWork = async (workId) => {
      if (confirm('确定要删除这个作品吗？')) {
        try {
          await userStore.deleteWork(workId);
          alert('作品已删除');
        } catch (error) {
          console.error('删除失败:', error);
          alert('删除失败，请重试');
        }
      }
    };

    const loadUserWorks = async () => {
      loading.value = true;
      try {
        await userStore.fetchUserWorks();
      } catch (error) {
        console.error('获取作品列表失败:', error);
      } finally {
        loading.value = false;
      }
    };

    onMounted(() => {
      // 组件挂载时获取用户作品
      loadUserWorks();
    });
</script>

<style scoped>
.user-works {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.works-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.works-header h2 {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.sort-select {
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: white;
  font-size: 14px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

.upload-btn .icon {
  font-size: 18px;
  font-weight: bold;
}

.works-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  overflow-x: auto;
  padding-bottom: 10px;
}

.filter-btn {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.filter-btn.active {
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  color: white;
  border-color: transparent;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 24px;
  margin-bottom: 10px;
  color: white;
}

.create-first-btn {
  margin-top: 20px;
  padding: 12px 24px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.create-first-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
}

.work-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.work-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.work-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.work-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.work-card:hover .work-image img {
  transform: scale(1.05);
}

.work-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.work-card:hover .work-overlay {
  opacity: 1;
}

.work-overlay button {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-btn {
  background: rgba(59, 130, 246, 0.8);
  color: white;
}

.edit-btn {
  background: rgba(251, 191, 36, 0.8);
  color: white;
}

.delete-btn {
  background: rgba(239, 68, 68, 0.8);
  color: white;
}

.work-content {
  padding: 20px;
}

.work-content h3 {
  color: white;
  margin-bottom: 10px;
  font-size: 18px;
  line-height: 1.4;
}

.work-description {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.work-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.tag {
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.work-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.6);
}

.stat .icon {
  font-size: 16px;
}

.work-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 15px;
}

.category {
  padding: 4px 8px;
  background: rgba(0, 212, 255, 0.2);
  border-radius: 8px;
  color: #00d4ff;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.upload-modal {
  background: rgba(26, 26, 46, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  color: white;
  margin: 0;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-form {
  padding: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: white;
  font-size: 14px;
}

.form-group input::placeholder,
.form-group textarea::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.file-upload {
  border: 2px dashed rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  transition: border-color 0.3s ease;
}

.file-upload:hover {
  border-color: #00d4ff;
}

.file-preview {
  margin-top: 15px;
}

.file-preview img {
  max-width: 200px;
  max-height: 150px;
  border-radius: 8px;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  color: rgba(255, 255, 255, 0.7);
}

.form-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 30px;
}

.cancel-btn {
  padding: 12px 24px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.submit-btn {
  padding: 12px 24px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 8px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 212, 255, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

@media (max-width: 768px) {
  .works-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
  }
  
  .works-grid {
    grid-template-columns: 1fr;
  }
  
  .upload-modal {
    width: 95%;
    margin: 20px;
  }
  
  .modal-header,
  .upload-form {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>